package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private VoucherOrderServiceImpl thisService;//注入本身
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final String LOCK_ORDER_KEY = "lock:order:";
//    private BlockingQueue<VoucherOrder> ordersTask = new ArrayBlockingQueue<>(1024*1024); //阻塞队列

    private static final ExecutorService executorService = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init() {
        executorService.submit(new voucherOrderHandler());
    }

    private class voucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    //1.获取消息队列中的订单信息
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed()));
                    //判断消息是否获取成功
                    if (list == null || list.isEmpty()) {
                        //获取失败，说明队列为空，继续下一次循环
                        continue;
                    }
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //获取成功，开始处理订单
                    handleVoucherOrder(voucherOrder);
                    //ack确认
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePendingList();
                }
            }
        }


    }

    private void handlePendingList() {
        while (true) {
//                RedisConnection connection = null;
            try {
//                    connection = stringRedisTemplate.getConnectionFactory().getConnection();
                //1.获取消息队列中的订单信息
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create("stream.orders", ReadOffset.from("0")));
                //判断消息是否获取成功
                if (list == null || list.isEmpty()) {
                    //获取失败，说明Pending-list中没有异常信息，结束循环
                    break;
                }
                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> value = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                //获取成功，开始处理订单
                handleVoucherOrder(voucherOrder);
                //ack确认
                stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
            } catch (Exception e) {
                log.error("处理pending-list异常", e);
            }
//                finally {
//                    if (connection != null){
//                        connection.close();
//                    }
//                }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //获取用户id
        Long userId = voucherOrder.getUserId();
        //加锁
        RLock lock = redissonClient.getLock(LOCK_ORDER_KEY + userId);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            log.error("不允许重复下单");
            return;
        }
        //3.创建订单
        try {
            thisService.createVoucherOrder(voucherOrder);
        }finally {
            //释放锁
            lock.unlock();
        }
    }

    //lua脚本
    private static final DefaultRedisScript<Long> SCRIPT;

    static {
        SCRIPT = new DefaultRedisScript<>();
        SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SCRIPT.setResultType(Long.class);
    }
    @Override
    public Result addOrder(Long voucherId) throws InterruptedException {
        //1. 获取用户
        Long id = UserHolder.getUser().getId();
        //2.查询代金券是否在合理时间内
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        LocalDateTime beginTime = seckillVoucher.getBeginTime();//代金券开始时间
        LocalDateTime endTime = seckillVoucher.getEndTime();//代金券结束时间
        if (LocalDateTime.now().isBefore(beginTime) || LocalDateTime.now().isAfter(endTime)){
            return Result.fail("不在时间范围内");
        }
//        //3.1先查询库存
//        if (seckillVoucher.getStock() < 1){
//            //库存不足
//            return Result.fail("库存不足");
//        }
        //3.2扣减库存
        //intern()返回字符串对象的规范表示形式
        /*
        锁的资源是用户id值，不是对象所以要调用intern方法保证同一个id值转化的字符串地址相同，同一个用户只能购买一次
        如果不加intern()，每次查询都会创建一个新的字符串对象，即使字符串的值相同，也会被分配到不同的内存地址上，从而导致锁的资源不同，导致线程安全问题
        如果将锁放在方法中，当方法执行完毕锁会被做释放，但这时事务还没提交，在事务提交时，锁已经被释放，其他线程可以进入，导致线程安全
        所以将锁放在方法外，事务提交后再释放锁，其他线程才能进入，保证线程安全
        但是使用this调用带事务的方法时，事务会失效。因为声明式事务底层使用的是AOP代理，使用this不会经过代理对象所以事务会失效。
        使用自注入来解决
         */
//      //单一服务器时
//        synchronized (id.toString().intern()) {
//            return thisService.createVoucherOrder(voucherId, id);
//        }
//        //集群时，有误删锁风险，需要使用lua脚本保证原子性来解决
//        //创建锁对象获取锁
//        SimpleRedisLock lock = new SimpleRedisLock("order:" + id, stringRedisTemplate);
//        boolean isLock = lock.tryLock(50L);
//        if (!isLock){
//            return Result.fail("不允许重复下单");
//        }
//        try {
//            return thisService.createVoucherOrder(voucherId, id);
//        }finally {
//            lock.unLock();
//        }

//        //使用Redisson分布式锁解决线程安全问题
//        RLock lock = redissonClient.getLock(LOCK_ORDER_KEY + id);
//        boolean isLock = lock.tryLock(1, TimeUnit.SECONDS);
//        if (!isLock) {
//            return Result.fail("不允许重复下单");
//        }
//        return thisService.createVoucherOrder(voucherId, id);
        //异步秒杀实现
        //执行lua脚本
        //生成订单号
        Long orderId = redisIdWorker.nextId("order");
        Long res = stringRedisTemplate.execute(SCRIPT, Collections.emptyList(),id.toString(),voucherId.toString(),orderId.toString());
        //判断返回值是否是0
        if (res.intValue() != 0){
            //不等于零说明秒杀失败
            return Result.fail(res == 1 ? "库存不足" : "不能重复下单");
        }

        return Result.ok(orderId);
    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
            //一人一单
            //查询订单中是否已经包含此用户id和代金券id
            Long id = voucherOrder.getUserId();
            Long voucherId = voucherOrder.getVoucherId();
            int count = query().eq("user_id", id).eq("voucher_id", voucherId).count();
            if (count > 0) {
                //该用户已经购买过
                log.error("该用户已经购买过");
                return;
            }
            boolean success = seckillVoucherService.update()
                    .setSql("stock = stock - 1")//设置sql语句
                    .eq("voucher_id", voucherId).gt("stock", 0)//where id =? and stock >?
                    .update();
            if (!success) {
                log.error("库存不足");
                return;
            }
            save(voucherOrder);
    }
}
